* Remove some hardcoded 0 instead of NS_MAIN
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
25
26 /**
27 * Database abstraction object
28 * @package MediaWiki
29 */
30 class Database {
31
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
37 */
38 var $mLastQuery = '';
39
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
42
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 /**#@-*/
48
49 #------------------------------------------------------------------------------
50 # Accessors
51 #------------------------------------------------------------------------------
52 # These optionally set a variable and return the previous state
53
54 /**
55 * Fail function, takes a Database as a parameter
56 * Set to false for default, 1 for ignore errors
57 */
58 function failFunction( $function = NULL ) {
59 return wfSetVar( $this->mFailFunction, $function );
60 }
61
62 /**
63 * Output page, used for reporting errors
64 * FALSE means discard output
65 */
66 function &setOutputPage( &$out ) {
67 $this->mOut =& $out;
68 }
69
70 /**
71 * Boolean, controls output of large amounts of debug information
72 */
73 function debug( $debug = NULL ) {
74 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
75 }
76
77 /**
78 * Turns buffering of SQL result sets on (true) or off (false).
79 * Default is "on" and it should not be changed without good reasons.
80 */
81 function bufferResults( $buffer = NULL ) {
82 if ( is_null( $buffer ) ) {
83 return !(bool)( $this->mFlags & DBO_NOBUFFER );
84 } else {
85 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
86 }
87 }
88
89 /**
90 * Turns on (false) or off (true) the automatic generation and sending
91 * of a "we're sorry, but there has been a database error" page on
92 * database errors. Default is on (false). When turned off, the
93 * code should use wfLastErrno() and wfLastError() to handle the
94 * situation as appropriate.
95 */
96 function ignoreErrors( $ignoreErrors = NULL ) {
97 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
98 }
99
100 /**
101 * The current depth of nested transactions
102 * @param integer $level
103 */
104 function trxLevel( $level = NULL ) {
105 return wfSetVar( $this->mTrxLevel, $level );
106 }
107
108 /**#@+
109 * Get function
110 */
111 function lastQuery() { return $this->mLastQuery; }
112 function isOpen() { return $this->mOpened; }
113 /**#@-*/
114
115 #------------------------------------------------------------------------------
116 # Other functions
117 #------------------------------------------------------------------------------
118
119 /**#@+
120 * @param string $server database server host
121 * @param string $user database user name
122 * @param string $password database user password
123 * @param string $dbname database name
124 */
125
126 /**
127 * @param failFunction
128 * @param $flags
129 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
130 */
131 function Database( $server = false, $user = false, $password = false, $dbName = false,
132 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
133
134 global $wgOut, $wgDBprefix, $wgCommandLineMode;
135 # Can't get a reference if it hasn't been set yet
136 if ( !isset( $wgOut ) ) {
137 $wgOut = NULL;
138 }
139 $this->mOut =& $wgOut;
140
141 $this->mFailFunction = $failFunction;
142 $this->mFlags = $flags;
143
144 if ( $this->mFlags & DBO_DEFAULT ) {
145 if ( $wgCommandLineMode ) {
146 $this->mFlags &= ~DBO_TRX;
147 } else {
148 $this->mFlags |= DBO_TRX;
149 }
150 }
151
152 /** Get the default table prefix*/
153 if ( $tablePrefix == 'get from global' ) {
154 $this->mTablePrefix = $wgDBprefix;
155 } else {
156 $this->mTablePrefix = $tablePrefix;
157 }
158
159 if ( $server ) {
160 $this->open( $server, $user, $password, $dbName );
161 }
162 }
163
164 /**
165 * @static
166 * @param failFunction
167 * @param $flags
168 */
169 function newFromParams( $server, $user, $password, $dbName,
170 $failFunction = false, $flags = 0 )
171 {
172 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
173 }
174
175 /**
176 * Usually aborts on failure
177 * If the failFunction is set to a non-zero integer, returns success
178 */
179 function open( $server, $user, $password, $dbName ) {
180 # Test for missing mysql.so
181 # First try to load it
182 if (!@extension_loaded('mysql')) {
183 @dl('mysql.so');
184 }
185
186 # Otherwise we get a suppressed fatal error, which is very hard to track down
187 if ( !function_exists( 'mysql_connect' ) ) {
188 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
189 }
190
191 $this->close();
192 $this->mServer = $server;
193 $this->mUser = $user;
194 $this->mPassword = $password;
195 $this->mDBname = $dbName;
196
197 $success = false;
198
199 @/**/$this->mConn = mysql_connect( $server, $user, $password );
200 if ( $dbName != '' ) {
201 if ( $this->mConn !== false ) {
202 $success = @/**/mysql_select_db( $dbName, $this->mConn );
203 if ( !$success ) {
204 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
205 }
206 } else {
207 wfDebug( "DB connection error\n" );
208 wfDebug( "Server: $server, User: $user, Password: " .
209 substr( $password, 0, 3 ) . "...\n" );
210 $success = false;
211 }
212 } else {
213 # Delay USE query
214 $success = !!$this->mConn;
215 }
216
217 if ( !$success ) {
218 $this->reportConnectionError();
219 $this->close();
220 }
221 $this->mOpened = $success;
222 return $success;
223 }
224 /**#@-*/
225
226 /**
227 * Closes a database connection.
228 * if it is open : commits any open transactions
229 *
230 * @return bool operation success. true if already closed.
231 */
232 function close()
233 {
234 $this->mOpened = false;
235 if ( $this->mConn ) {
236 if ( $this->trxLevel() ) {
237 $this->immediateCommit();
238 }
239 return mysql_close( $this->mConn );
240 } else {
241 return true;
242 }
243 }
244
245 /**
246 * @access private
247 * @param string $msg error message ?
248 * @todo parameter $msg is not used
249 */
250 function reportConnectionError( $msg = '') {
251 if ( $this->mFailFunction ) {
252 if ( !is_int( $this->mFailFunction ) ) {
253 $ff = $this->mFailFunction;
254 $ff( $this, mysql_error() );
255 }
256 } else {
257 wfEmergencyAbort( $this, mysql_error() );
258 }
259 }
260
261 /**
262 * Usually aborts on failure
263 * If errors are explicitly ignored, returns success
264 */
265 function query( $sql, $fname = '', $tempIgnore = false ) {
266 global $wgProfiling, $wgCommandLineMode;
267
268 if ( $wgProfiling ) {
269 # generalizeSQL will probably cut down the query to reasonable
270 # logging size most of the time. The substr is really just a sanity check.
271 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
272 wfProfileIn( $profName );
273 }
274
275 $this->mLastQuery = $sql;
276
277 if ( $this->debug() ) {
278 $sqlx = substr( $sql, 0, 500 );
279 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
280 wfDebug( "SQL: $sqlx\n" );
281 }
282 # Add a comment for easy SHOW PROCESSLIST interpretation
283 if ( $fname ) {
284 $commentedSql = "/* $fname */ $sql";
285 } else {
286 $commentedSql = $sql;
287 }
288
289 # If DBO_TRX is set, start a transaction
290 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
291 $this->begin();
292 }
293
294 # Do the query and handle errors
295 $ret = $this->doQuery( $commentedSql );
296 if ( false === $ret ) {
297 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
298 }
299
300 if ( $wgProfiling ) {
301 wfProfileOut( $profName );
302 }
303 return $ret;
304 }
305
306 /**
307 * The DBMS-dependent part of query()
308 * @param string $sql SQL query.
309 */
310 function doQuery( $sql ) {
311 if( $this->bufferResults() ) {
312 $ret = mysql_query( $sql, $this->mConn );
313 } else {
314 $ret = mysql_unbuffered_query( $sql, $this->mConn );
315 }
316 return $ret;
317 }
318
319 /**
320 * @param $error
321 * @param $errno
322 * @param $sql
323 * @param string $fname
324 * @param bool $tempIgnore
325 */
326 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
327 global $wgCommandLineMode, $wgFullyInitialised;
328 # Ignore errors during error handling to avoid infinite recursion
329 $ignore = $this->ignoreErrors( true );
330
331 if( $ignore || $tempIgnore ) {
332 wfDebug("SQL ERROR (ignored): " . $error . "\n");
333 } else {
334 $sql1line = str_replace( "\n", "\\n", $sql );
335 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
336 wfDebug("SQL ERROR: " . $error . "\n");
337 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
338 $message = "A database error has occurred\n" .
339 "Query: $sql\n" .
340 "Function: $fname\n" .
341 "Error: $errno $error\n";
342 if ( !$wgCommandLineMode ) {
343 $message = nl2br( $message );
344 }
345 wfDebugDieBacktrace( $message );
346 } else {
347 // this calls wfAbruptExit()
348 $this->mOut->databaseError( $fname, $sql, $error, $errno );
349 }
350 }
351 $this->ignoreErrors( $ignore );
352 }
353
354
355 /**
356 * Intended to be compatible with the PEAR::DB wrapper functions.
357 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
358 *
359 * ? = scalar value, quoted as necessary
360 * ! = raw SQL bit (a function for instance)
361 * & = filename; reads the file and inserts as a blob
362 * (we don't use this though...)
363 */
364 function prepare( $sql, $func = 'Database::prepare' ) {
365 /* MySQL doesn't support prepared statements (yet), so just
366 pack up the query for reference. We'll manually replace
367 the bits later. */
368 return array( 'query' => $sql, 'func' => $func );
369 }
370
371 function freePrepared( $prepared ) {
372 /* No-op for MySQL */
373 }
374
375 /**
376 * Execute a prepared query with the various arguments
377 * @param string $prepared the prepared sql
378 * @param mixed $args Either an array here, or put scalars as varargs
379 */
380 function execute( $prepared, $args = null ) {
381 if( !is_array( $args ) ) {
382 # Pull the var args
383 $args = func_get_args();
384 array_shift( $args );
385 }
386 $sql = $this->fillPrepared( $prepared['query'], $args );
387 return $this->query( $sql, $prepared['func'] );
388 }
389
390 /**
391 * Prepare & execute an SQL statement, quoting and inserting arguments
392 * in the appropriate places.
393 * @param
394 */
395 function safeQuery( $query, $args = null ) {
396 $prepared = $this->prepare( $query, 'Database::safeQuery' );
397 if( !is_array( $args ) ) {
398 # Pull the var args
399 $args = func_get_args();
400 array_shift( $args );
401 }
402 $retval = $this->execute( $prepared, $args );
403 $this->freePrepared( $prepared );
404 return $retval;
405 }
406
407 /**
408 * For faking prepared SQL statements on DBs that don't support
409 * it directly.
410 * @param string $preparedSql - a 'preparable' SQL statement
411 * @param array $args - array of arguments to fill it with
412 * @return string executable SQL
413 */
414 function fillPrepared( $preparedQuery, $args ) {
415 $n = 0;
416 reset( $args );
417 $this->preparedArgs =& $args;
418 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
419 array( &$this, 'fillPreparedArg' ), $preparedQuery );
420 }
421
422 /**
423 * preg_callback func for fillPrepared()
424 * The arguments should be in $this->preparedArgs and must not be touched
425 * while we're doing this.
426 *
427 * @param array $matches
428 * @return string
429 * @access private
430 */
431 function fillPreparedArg( $matches ) {
432 switch( $matches[1] ) {
433 case '\\?': return '?';
434 case '\\!': return '!';
435 case '\\&': return '&';
436 }
437 list( $n, $arg ) = each( $this->preparedArgs );
438 switch( $matches[1] ) {
439 case '?': return $this->addQuotes( $arg );
440 case '!': return $arg;
441 case '&':
442 # return $this->addQuotes( file_get_contents( $arg ) );
443 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
444 default:
445 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
446 }
447 }
448
449 /**#@+
450 * @param mixed $res A SQL result
451 */
452 /**
453 * Free a result object
454 */
455 function freeResult( $res ) {
456 if ( !@/**/mysql_free_result( $res ) ) {
457 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
458 }
459 }
460
461 /**
462 * Fetch the next row from the given result object, in object form
463 */
464 function fetchObject( $res ) {
465 @/**/$row = mysql_fetch_object( $res );
466 if( mysql_errno() ) {
467 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
468 }
469 return $row;
470 }
471
472 /**
473 * Fetch the next row from the given result object
474 * Returns an array
475 */
476 function fetchRow( $res ) {
477 @/**/$row = mysql_fetch_array( $res );
478 if (mysql_errno() ) {
479 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
480 }
481 return $row;
482 }
483
484 /**
485 * Get the number of rows in a result object
486 */
487 function numRows( $res ) {
488 @/**/$n = mysql_num_rows( $res );
489 if( mysql_errno() ) {
490 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
491 }
492 return $n;
493 }
494
495 /**
496 * Get the number of fields in a result object
497 * See documentation for mysql_num_fields()
498 */
499 function numFields( $res ) { return mysql_num_fields( $res ); }
500
501 /**
502 * Get a field name in a result object
503 * See documentation for mysql_field_name()
504 */
505 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
506
507 /**
508 * Get the inserted value of an auto-increment row
509 *
510 * The value inserted should be fetched from nextSequenceValue()
511 *
512 * Example:
513 * $id = $dbw->nextSequenceValue('cur_cur_id_seq');
514 * $dbw->insert('cur',array('cur_id' => $id));
515 * $id = $dbw->insertId();
516 */
517 function insertId() { return mysql_insert_id( $this->mConn ); }
518
519 /**
520 * Change the position of the cursor in a result object
521 * See mysql_data_seek()
522 */
523 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
524
525 /**
526 * Get the last error number
527 * See mysql_errno()
528 */
529 function lastErrno() { return mysql_errno(); }
530
531 /**
532 * Get a description of the last error
533 * See mysql_error() for more details
534 */
535 function lastError() { return mysql_error(); }
536
537 /**
538 * Get the number of rows affected by the last write query
539 * See mysql_affected_rows() for more details
540 */
541 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
542 /**#@-*/ // end of template : @param $result
543
544 /**
545 * Simple UPDATE wrapper
546 * Usually aborts on failure
547 * If errors are explicitly ignored, returns success
548 *
549 * This function exists for historical reasons, Database::update() has a more standard
550 * calling convention and feature set
551 */
552 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
553 {
554 $table = $this->tableName( $table );
555 $sql = "UPDATE $table SET $var = '" .
556 $this->strencode( $value ) . "' WHERE ($cond)";
557 return !!$this->query( $sql, DB_MASTER, $fname );
558 }
559
560 /**
561 * Simple SELECT wrapper, returns a single field, input must be encoded
562 * Usually aborts on failure
563 * If errors are explicitly ignored, returns FALSE on failure
564 */
565 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
566 if ( !is_array( $options ) ) {
567 $options = array( $options );
568 }
569 $options['LIMIT'] = 1;
570
571 $res = $this->select( $table, $var, $cond, $fname, $options );
572 if ( $res === false || !$this->numRows( $res ) ) {
573 return false;
574 }
575 $row = $this->fetchRow( $res );
576 if ( $row !== false ) {
577 $this->freeResult( $res );
578 return $row[0];
579 } else {
580 return false;
581 }
582 }
583
584 /**
585 * Returns an optional USE INDEX clause to go after the table, and a
586 * string to go at the end of the query
587 */
588 function makeSelectOptions( $options ) {
589 if ( !is_array( $options ) ) {
590 $options = array( $options );
591 }
592
593 $tailOpts = '';
594
595 if ( isset( $options['ORDER BY'] ) ) {
596 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
597 }
598 if ( isset( $options['LIMIT'] ) ) {
599 $tailOpts .= " LIMIT {$options['LIMIT']}";
600 }
601
602 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
603 $tailOpts .= ' FOR UPDATE';
604 }
605
606 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
607 $tailOpts .= ' LOCK IN SHARE MODE';
608 }
609
610 if ( isset( $options['USE INDEX'] ) ) {
611 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
612 } else {
613 $useIndex = '';
614 }
615 return array( $useIndex, $tailOpts );
616 }
617
618 /**
619 * SELECT wrapper
620 */
621 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
622 {
623 if( is_array( $vars ) ) {
624 $vars = implode( ',', $vars );
625 }
626 if( is_array( $table ) ) {
627 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
628 } elseif ($table!='') {
629 $from = ' FROM ' .$this->tableName( $table );
630 } else {
631 $from = '';
632 }
633
634 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
635
636 if( !empty( $conds ) ) {
637 if ( is_array( $conds ) ) {
638 $conds = $this->makeList( $conds, LIST_AND );
639 }
640 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
641 } else {
642 $sql = "SELECT $vars $from $useIndex $tailOpts";
643 }
644 return $this->query( $sql, $fname );
645 }
646
647 /**
648 * Single row SELECT wrapper
649 * Aborts or returns FALSE on error
650 *
651 * $vars: the selected variables
652 * $conds: a condition map, terms are ANDed together.
653 * Items with numeric keys are taken to be literal conditions
654 * Takes an array of selected variables, and a condition map, which is ANDed
655 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
656 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
657 * $obj- >page_id is the ID of the Astronomy article
658 *
659 * @todo migrate documentation to phpdocumentor format
660 */
661 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
662 $options['LIMIT'] = 1;
663 $res = $this->select( $table, $vars, $conds, $fname, $options );
664 if ( $res === false || !$this->numRows( $res ) ) {
665 return false;
666 }
667 $obj = $this->fetchObject( $res );
668 $this->freeResult( $res );
669 return $obj;
670
671 }
672
673 /**
674 * Removes most variables from an SQL query and replaces them with X or N for numbers.
675 * It's only slightly flawed. Don't use for anything important.
676 *
677 * @param string $sql A SQL Query
678 * @static
679 */
680 function generalizeSQL( $sql ) {
681 # This does the same as the regexp below would do, but in such a way
682 # as to avoid crashing php on some large strings.
683 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
684
685 $sql = str_replace ( "\\\\", '', $sql);
686 $sql = str_replace ( "\\'", '', $sql);
687 $sql = str_replace ( "\\\"", '', $sql);
688 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
689 $sql = preg_replace ('/".*"/s', "'X'", $sql);
690
691 # All newlines, tabs, etc replaced by single space
692 $sql = preg_replace ( "/\s+/", ' ', $sql);
693
694 # All numbers => N
695 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
696
697 return $sql;
698 }
699
700 /**
701 * Determines whether a field exists in a table
702 * Usually aborts on failure
703 * If errors are explicitly ignored, returns NULL on failure
704 */
705 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
706 $table = $this->tableName( $table );
707 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
708 if ( !$res ) {
709 return NULL;
710 }
711
712 $found = false;
713
714 while ( $row = $this->fetchObject( $res ) ) {
715 if ( $row->Field == $field ) {
716 $found = true;
717 break;
718 }
719 }
720 return $found;
721 }
722
723 /**
724 * Determines whether an index exists
725 * Usually aborts on failure
726 * If errors are explicitly ignored, returns NULL on failure
727 */
728 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
729 $info = $this->indexInfo( $table, $index, $fname );
730 if ( is_null( $info ) ) {
731 return NULL;
732 } else {
733 return $info !== false;
734 }
735 }
736
737
738 /**
739 * Get information about an index into an object
740 * Returns false if the index does not exist
741 */
742 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
743 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
744 # SHOW INDEX should work for 3.x and up:
745 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
746 $table = $this->tableName( $table );
747 $sql = 'SHOW INDEX FROM '.$table;
748 $res = $this->query( $sql, $fname );
749 if ( !$res ) {
750 return NULL;
751 }
752
753 while ( $row = $this->fetchObject( $res ) ) {
754 if ( $row->Key_name == $index ) {
755 return $row;
756 }
757 }
758 return false;
759 }
760
761 /**
762 * Query whether a given table exists
763 */
764 function tableExists( $table ) {
765 $table = $this->tableName( $table );
766 $old = $this->ignoreErrors( true );
767 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
768 $this->ignoreErrors( $old );
769 if( $res ) {
770 $this->freeResult( $res );
771 return true;
772 } else {
773 return false;
774 }
775 }
776
777 /**
778 * mysql_fetch_field() wrapper
779 * Returns false if the field doesn't exist
780 *
781 * @param $table
782 * @param $field
783 */
784 function fieldInfo( $table, $field ) {
785 $table = $this->tableName( $table );
786 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
787 $n = mysql_num_fields( $res );
788 for( $i = 0; $i < $n; $i++ ) {
789 $meta = mysql_fetch_field( $res, $i );
790 if( $field == $meta->name ) {
791 return $meta;
792 }
793 }
794 return false;
795 }
796
797 /**
798 * mysql_field_type() wrapper
799 */
800 function fieldType( $res, $index ) {
801 return mysql_field_type( $res, $index );
802 }
803
804 /**
805 * Determines if a given index is unique
806 */
807 function indexUnique( $table, $index ) {
808 $indexInfo = $this->indexInfo( $table, $index );
809 if ( !$indexInfo ) {
810 return NULL;
811 }
812 return !$indexInfo->Non_unique;
813 }
814
815 /**
816 * INSERT wrapper, inserts an array into a table
817 *
818 * $a may be a single associative array, or an array of these with numeric keys, for
819 * multi-row insert.
820 *
821 * Usually aborts on failure
822 * If errors are explicitly ignored, returns success
823 */
824 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
825 # No rows to insert, easy just return now
826 if ( !count( $a ) ) {
827 return true;
828 }
829
830 $table = $this->tableName( $table );
831 if ( !is_array( $options ) ) {
832 $options = array( $options );
833 }
834 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
835 $multi = true;
836 $keys = array_keys( $a[0] );
837 } else {
838 $multi = false;
839 $keys = array_keys( $a );
840 }
841
842 $sql = 'INSERT ' . implode( ' ', $options ) .
843 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
844
845 if ( $multi ) {
846 $first = true;
847 foreach ( $a as $row ) {
848 if ( $first ) {
849 $first = false;
850 } else {
851 $sql .= ',';
852 }
853 $sql .= '(' . $this->makeList( $row ) . ')';
854 }
855 } else {
856 $sql .= '(' . $this->makeList( $a ) . ')';
857 }
858 return !!$this->query( $sql, $fname );
859 }
860
861 /**
862 * UPDATE wrapper, takes a condition array and a SET array
863 */
864 function update( $table, $values, $conds, $fname = 'Database::update' ) {
865 $table = $this->tableName( $table );
866 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
867 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
868 $this->query( $sql, $fname );
869 }
870
871 /**
872 * Makes a wfStrencoded list from an array
873 * $mode: LIST_COMMA - comma separated, no field names
874 * LIST_AND - ANDed WHERE clause (without the WHERE)
875 * LIST_SET - comma separated with field names, like a SET clause
876 * LIST_NAMES - comma separated field names
877 */
878 function makeList( $a, $mode = LIST_COMMA ) {
879 if ( !is_array( $a ) ) {
880 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
881 }
882
883 $first = true;
884 $list = '';
885 foreach ( $a as $field => $value ) {
886 if ( !$first ) {
887 if ( $mode == LIST_AND ) {
888 $list .= ' AND ';
889 } else {
890 $list .= ',';
891 }
892 } else {
893 $first = false;
894 }
895 if ( $mode == LIST_AND && is_numeric( $field ) ) {
896 $list .= "($value)";
897 } elseif ( $mode == LIST_AND && is_array ($value) ) {
898 $list .= $field." IN (".$this->makeList($value).") ";
899 } else {
900 if ( $mode == LIST_AND || $mode == LIST_SET ) {
901 $list .= $field.'=';
902 }
903 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
904 }
905 }
906 return $list;
907 }
908
909 /**
910 * Change the current database
911 */
912 function selectDB( $db ) {
913 $this->mDBname = $db;
914 return mysql_select_db( $db, $this->mConn );
915 }
916
917 /**
918 * Starts a timer which will kill the DB thread after $timeout seconds
919 */
920 function startTimer( $timeout ) {
921 global $IP;
922 if( function_exists( 'mysql_thread_id' ) ) {
923 # This will kill the query if it's still running after $timeout seconds.
924 $tid = mysql_thread_id( $this->mConn );
925 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
926 }
927 }
928
929 /**
930 * Stop a timer started by startTimer()
931 * Currently unimplemented.
932 *
933 */
934 function stopTimer() { }
935
936 /**
937 * Format a table name ready for use in constructing an SQL query
938 *
939 * This does two important things: it quotes table names which as necessary,
940 * and it adds a table prefix if there is one.
941 *
942 * All functions of this object which require a table name call this function
943 * themselves. Pass the canonical name to such functions. This is only needed
944 * when calling query() directly.
945 *
946 * @param string $name database table name
947 */
948 function tableName( $name ) {
949 global $wgSharedDB;
950 if ( $this->mTablePrefix !== '' ) {
951 if ( strpos( '.', $name ) === false ) {
952 $name = $this->mTablePrefix . $name;
953 }
954 }
955 if ( isset( $wgSharedDB ) && 'user' == $name ) {
956 $name = $wgSharedDB . '.' . $name;
957 }
958 if( $name == 'group' ) {
959 $name = '`' . $name . '`';
960 }
961 return $name;
962 }
963
964 /**
965 * Fetch a number of table names into an array
966 * This is handy when you need to construct SQL for joins
967 *
968 * Example:
969 * extract($dbr->tableNames('user','watchlist'));
970 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
971 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
972 */
973 function tableNames() {
974 $inArray = func_get_args();
975 $retVal = array();
976 foreach ( $inArray as $name ) {
977 $retVal[$name] = $this->tableName( $name );
978 }
979 return $retVal;
980 }
981
982 /**
983 * Wrapper for addslashes()
984 * @param string $s String to be slashed.
985 * @return string slashed string.
986 */
987 function strencode( $s ) {
988 return addslashes( $s );
989 }
990
991 /**
992 * If it's a string, adds quotes and backslashes
993 * Otherwise returns as-is
994 */
995 function addQuotes( $s ) {
996 if ( is_null( $s ) ) {
997 $s = 'NULL';
998 } else {
999 # This will also quote numeric values. This should be harmless,
1000 # and protects against weird problems that occur when they really
1001 # _are_ strings such as article titles and string->number->string
1002 # conversion is not 1:1.
1003 $s = "'" . $this->strencode( $s ) . "'";
1004 }
1005 return $s;
1006 }
1007
1008 /**
1009 * Returns an appropriately quoted sequence value for inserting a new row.
1010 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1011 * subclass will return an integer, and save the value for insertId()
1012 */
1013 function nextSequenceValue( $seqName ) {
1014 return NULL;
1015 }
1016
1017 /**
1018 * USE INDEX clause
1019 * PostgreSQL doesn't have them and returns ""
1020 */
1021 function useIndexClause( $index ) {
1022 return 'USE INDEX ('.$index.')';
1023 }
1024
1025 /**
1026 * REPLACE query wrapper
1027 * PostgreSQL simulates this with a DELETE followed by INSERT
1028 * $row is the row to insert, an associative array
1029 * $uniqueIndexes is an array of indexes. Each element may be either a
1030 * field name or an array of field names
1031 *
1032 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1033 * However if you do this, you run the risk of encountering errors which wouldn't have
1034 * occurred in MySQL
1035 *
1036 * @todo migrate comment to phodocumentor format
1037 */
1038 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1039 $table = $this->tableName( $table );
1040
1041 # Single row case
1042 if ( !is_array( reset( $rows ) ) ) {
1043 $rows = array( $rows );
1044 }
1045
1046 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1047 $first = true;
1048 foreach ( $rows as $row ) {
1049 if ( $first ) {
1050 $first = false;
1051 } else {
1052 $sql .= ',';
1053 }
1054 $sql .= '(' . $this->makeList( $row ) . ')';
1055 }
1056 return $this->query( $sql, $fname );
1057 }
1058
1059 /**
1060 * DELETE where the condition is a join
1061 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1062 *
1063 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1064 * join condition matches, set $conds='*'
1065 *
1066 * DO NOT put the join condition in $conds
1067 *
1068 * @param string $delTable The table to delete from.
1069 * @param string $joinTable The other table.
1070 * @param string $delVar The variable to join on, in the first table.
1071 * @param string $joinVar The variable to join on, in the second table.
1072 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1073 */
1074 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1075 if ( !$conds ) {
1076 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1077 }
1078
1079 $delTable = $this->tableName( $delTable );
1080 $joinTable = $this->tableName( $joinTable );
1081 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1082 if ( $conds != '*' ) {
1083 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1084 }
1085
1086 return $this->query( $sql, $fname );
1087 }
1088
1089 /**
1090 * Returns the size of a text field, or -1 for "unlimited"
1091 */
1092 function textFieldSize( $table, $field ) {
1093 $table = $this->tableName( $table );
1094 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1095 $res = $this->query( $sql, 'Database::textFieldSize' );
1096 $row = $this->fetchObject( $res );
1097 $this->freeResult( $res );
1098
1099 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1100 $size = $m[1];
1101 } else {
1102 $size = -1;
1103 }
1104 return $size;
1105 }
1106
1107 /**
1108 * @return string Always return 'LOW_PRIORITY'
1109 */
1110 function lowPriorityOption() {
1111 return 'LOW_PRIORITY';
1112 }
1113
1114 /**
1115 * DELETE query wrapper
1116 *
1117 * Use $conds == "*" to delete all rows
1118 */
1119 function delete( $table, $conds, $fname = 'Database::delete' ) {
1120 if ( !$conds ) {
1121 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1122 }
1123 $table = $this->tableName( $table );
1124 $sql = "DELETE FROM $table ";
1125 if ( $conds != '*' ) {
1126 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1127 }
1128 return $this->query( $sql, $fname );
1129 }
1130
1131 /**
1132 * INSERT SELECT wrapper
1133 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1134 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1135 * $conds may be "*" to copy the whole table
1136 */
1137 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1138 $destTable = $this->tableName( $destTable );
1139 $srcTable = $this->tableName( $srcTable );
1140 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1141 ' SELECT ' . implode( ',', $varMap ) .
1142 " FROM $srcTable";
1143 if ( $conds != '*' ) {
1144 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1145 }
1146 return $this->query( $sql, $fname );
1147 }
1148
1149 /**
1150 * Construct a LIMIT query with optional offset
1151 * This is used for query pages
1152 */
1153 function limitResult($limit,$offset) {
1154 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1155 }
1156
1157 /**
1158 * Returns an SQL expression for a simple conditional.
1159 * Uses IF on MySQL.
1160 *
1161 * @param string $cond SQL expression which will result in a boolean value
1162 * @param string $trueVal SQL expression to return if true
1163 * @param string $falseVal SQL expression to return if false
1164 * @return string SQL fragment
1165 */
1166 function conditional( $cond, $trueVal, $falseVal ) {
1167 return " IF($cond, $trueVal, $falseVal) ";
1168 }
1169
1170 /**
1171 * Determines if the last failure was due to a deadlock
1172 */
1173 function wasDeadlock() {
1174 return $this->lastErrno() == 1213;
1175 }
1176
1177 /**
1178 * Perform a deadlock-prone transaction.
1179 *
1180 * This function invokes a callback function to perform a set of write
1181 * queries. If a deadlock occurs during the processing, the transaction
1182 * will be rolled back and the callback function will be called again.
1183 *
1184 * Usage:
1185 * $dbw->deadlockLoop( callback, ... );
1186 *
1187 * Extra arguments are passed through to the specified callback function.
1188 *
1189 * Returns whatever the callback function returned on its successful,
1190 * iteration, or false on error, for example if the retry limit was
1191 * reached.
1192 */
1193 function deadlockLoop() {
1194 $myFname = 'Database::deadlockLoop';
1195
1196 $this->query( 'BEGIN', $myFname );
1197 $args = func_get_args();
1198 $function = array_shift( $args );
1199 $oldIgnore = $dbw->ignoreErrors( true );
1200 $tries = DEADLOCK_TRIES;
1201 if ( is_array( $function ) ) {
1202 $fname = $function[0];
1203 } else {
1204 $fname = $function;
1205 }
1206 do {
1207 $retVal = call_user_func_array( $function, $args );
1208 $error = $this->lastError();
1209 $errno = $this->lastErrno();
1210 $sql = $this->lastQuery();
1211
1212 if ( $errno ) {
1213 if ( $dbw->wasDeadlock() ) {
1214 # Retry
1215 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1216 } else {
1217 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1218 }
1219 }
1220 } while( $dbw->wasDeadlock && --$tries > 0 );
1221 $this->ignoreErrors( $oldIgnore );
1222 if ( $tries <= 0 ) {
1223 $this->query( 'ROLLBACK', $myFname );
1224 $this->reportQueryError( $error, $errno, $sql, $fname );
1225 return false;
1226 } else {
1227 $this->query( 'COMMIT', $myFname );
1228 return $retVal;
1229 }
1230 }
1231
1232 /**
1233 * Do a SELECT MASTER_POS_WAIT()
1234 *
1235 * @param string $file the binlog file
1236 * @param string $pos the binlog position
1237 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1238 */
1239 function masterPosWait( $file, $pos, $timeout ) {
1240 $fname = 'Database::masterPosWait';
1241 wfProfileIn( $fname );
1242
1243
1244 # Commit any open transactions
1245 $this->immediateCommit();
1246
1247 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1248 $encFile = $this->strencode( $file );
1249 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1250 $res = $this->doQuery( $sql );
1251 if ( $res && $row = $this->fetchRow( $res ) ) {
1252 $this->freeResult( $res );
1253 return $row[0];
1254 } else {
1255 return false;
1256 }
1257 }
1258
1259 /**
1260 * Get the position of the master from SHOW SLAVE STATUS
1261 */
1262 function getSlavePos() {
1263 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1264 $row = $this->fetchObject( $res );
1265 if ( $row ) {
1266 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1267 } else {
1268 return array( false, false );
1269 }
1270 }
1271
1272 /**
1273 * Get the position of the master from SHOW MASTER STATUS
1274 */
1275 function getMasterPos() {
1276 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1277 $row = $this->fetchObject( $res );
1278 if ( $row ) {
1279 return array( $row->File, $row->Position );
1280 } else {
1281 return array( false, false );
1282 }
1283 }
1284
1285 /**
1286 * Begin a transaction, or if a transaction has already started, continue it
1287 */
1288 function begin( $fname = 'Database::begin' ) {
1289 if ( !$this->mTrxLevel ) {
1290 $this->immediateBegin( $fname );
1291 } else {
1292 $this->mTrxLevel++;
1293 }
1294 }
1295
1296 /**
1297 * End a transaction, or decrement the nest level if transactions are nested
1298 */
1299 function commit( $fname = 'Database::commit' ) {
1300 if ( $this->mTrxLevel ) {
1301 $this->mTrxLevel--;
1302 }
1303 if ( !$this->mTrxLevel ) {
1304 $this->immediateCommit( $fname );
1305 }
1306 }
1307
1308 /**
1309 * Rollback a transaction
1310 */
1311 function rollback( $fname = 'Database::rollback' ) {
1312 $this->query( 'ROLLBACK', $fname );
1313 $this->mTrxLevel = 0;
1314 }
1315
1316 /**
1317 * Begin a transaction, committing any previously open transaction
1318 */
1319 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1320 $this->query( 'BEGIN', $fname );
1321 $this->mTrxLevel = 1;
1322 }
1323
1324 /**
1325 * Commit transaction, if one is open
1326 */
1327 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1328 $this->query( 'COMMIT', $fname );
1329 $this->mTrxLevel = 0;
1330 }
1331
1332 /**
1333 * Return MW-style timestamp used for MySQL schema
1334 */
1335 function timestamp( $ts=0 ) {
1336 return wfTimestamp(TS_MW,$ts);
1337 }
1338
1339 /**
1340 * @todo document
1341 */
1342 function &resultObject( &$result ) {
1343 if( empty( $result ) ) {
1344 return NULL;
1345 } else {
1346 return new ResultWrapper( $this, $result );
1347 }
1348 }
1349
1350 /**
1351 * Return aggregated value alias
1352 */
1353 function aggregateValue ($valuedata,$valuename='value') {
1354 return $valuename;
1355 }
1356
1357 /**
1358 * @return string wikitext of a link to the server software's web site
1359 */
1360 function getSoftwareLink() {
1361 return "[http://www.mysql.com/ MySQL]";
1362 }
1363
1364 /**
1365 * @return string Version information from the database
1366 */
1367 function getServerVersion() {
1368 return mysql_get_server_info();
1369 }
1370 }
1371
1372 /**
1373 * Database abstraction object for mySQL
1374 * Inherit all methods and properties of Database::Database()
1375 *
1376 * @package MediaWiki
1377 * @see Database
1378 */
1379 class DatabaseMysql extends Database {
1380 # Inherit all
1381 }
1382
1383
1384 /**
1385 * Result wrapper for grabbing data queried by someone else
1386 *
1387 * @package MediaWiki
1388 */
1389 class ResultWrapper {
1390 var $db, $result;
1391
1392 /**
1393 * @todo document
1394 */
1395 function ResultWrapper( $database, $result ) {
1396 $this->db =& $database;
1397 $this->result =& $result;
1398 }
1399
1400 /**
1401 * @todo document
1402 */
1403 function numRows() {
1404 return $this->db->numRows( $this->result );
1405 }
1406
1407 /**
1408 * @todo document
1409 */
1410 function &fetchObject() {
1411 return $this->db->fetchObject( $this->result );
1412 }
1413
1414 /**
1415 * @todo document
1416 */
1417 function &fetchRow() {
1418 return $this->db->fetchRow( $this->result );
1419 }
1420
1421 /**
1422 * @todo document
1423 */
1424 function free() {
1425 $this->db->freeResult( $this->result );
1426 unset( $this->result );
1427 unset( $this->db );
1428 }
1429 }
1430
1431 #------------------------------------------------------------------------------
1432 # Global functions
1433 #------------------------------------------------------------------------------
1434
1435 /**
1436 * Standard fail function, called by default when a connection cannot be
1437 * established.
1438 * Displays the file cache if possible
1439 */
1440 function wfEmergencyAbort( &$conn, $error ) {
1441 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1442 global $wgSitename, $wgServer;
1443
1444 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1445 # Hard coding strings instead.
1446
1447 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1448 $1';
1449 $mainpage = 'Main Page';
1450 $searchdisabled = <<<EOT
1451 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1452 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1453 EOT;
1454
1455 $googlesearch = "
1456 <!-- SiteSearch Google -->
1457 <FORM method=GET action=\"http://www.google.com/search\">
1458 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1459 <A HREF=\"http://www.google.com/\">
1460 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1461 border=\"0\" ALT=\"Google\"></A>
1462 </td>
1463 <td>
1464 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1465 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1466 <font size=-1>
1467 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
1468 <input type='hidden' name='ie' value='$2'>
1469 <input type='hidden' name='oe' value='$2'>
1470 </font>
1471 </td></tr></TABLE>
1472 </FORM>
1473 <!-- SiteSearch Google -->";
1474 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1475
1476
1477 if( !headers_sent() ) {
1478 header( 'HTTP/1.0 500 Internal Server Error' );
1479 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1480 /* Don't cache error pages! They cause no end of trouble... */
1481 header( 'Cache-control: none' );
1482 header( 'Pragma: nocache' );
1483 }
1484 $msg = $wgSiteNotice;
1485 if($msg == '') {
1486 $msg = str_replace( '$1', $error, $noconnect );
1487 }
1488 $text = $msg;
1489
1490 if($wgUseFileCache) {
1491 if($wgTitle) {
1492 $t =& $wgTitle;
1493 } else {
1494 if($title) {
1495 $t = Title::newFromURL( $title );
1496 } elseif (@/**/$_REQUEST['search']) {
1497 $search = $_REQUEST['search'];
1498 echo $searchdisabled;
1499 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1500 $wgInputEncoding ), $googlesearch );
1501 wfErrorExit();
1502 } else {
1503 $t = Title::newFromText( $mainpage );
1504 }
1505 }
1506
1507 $cache = new CacheManager( $t );
1508 if( $cache->isFileCached() ) {
1509 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1510 $cachederror . "</b></p>\n";
1511
1512 $tag = '<div id="article">';
1513 $text = str_replace(
1514 $tag,
1515 $tag . $msg,
1516 $cache->fetchPageText() );
1517 }
1518 }
1519
1520 echo $text;
1521 wfErrorExit();
1522 }
1523
1524 ?>